package com.cloud.common.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cloud.common.constant.GenConstants;
import com.cloud.generator.domain.GenTable;
import com.cloud.generator.domain.GenTableColumn;
import com.cloud.utils.DateUtils;
import com.cloud.utils.StringUtils;
import org.apache.velocity.VelocityContext;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 模板处理工具类
 *
 * @author yzj
 */
public class VelocityUtils {

    // 项目空间路径
    public static final String PROJECT_PATH = "main/java";

    // 项目包命名路径
    public static final String PACKAGE_PATH = "com.cloud";

    // Mybatis空间路径
    public static final String MYBATIS_PATH = "main/resources/mapper";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable) {
        VelocityContext context = new VelocityContext();
        context.put("tplCategory", genTable.getTplCategory());
        context.put("tableName", genTable.getTableName());
        context.put("functionName", genTable.getFunctionName());
        context.put("ClassName", genTable.getClassName());
        context.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        context.put("moduleName", genTable.getModuleName());
        context.put("businessName", StringUtils.uncapitalize(genTable.getBusinessName()));
        context.put("BusinessName", genTable.getBusinessName());
        context.put("packAgeName", genTable.getPackageName());
        context.put("author", genTable.getFunctionAuthor());
        context.put("dateTime", DateUtils.getDate());
        context.put("pkColumn", genTable.getPkColumn());
        context.put("importList", getImportList(genTable));
        context.put("columns", genTable.getColumns());
        context.put("table", genTable);
        context.put("dictList", getDictList(genTable));
        // 设置菜单上级主键
        context.put("parentMenuId", genTable.getParentMenuId());
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            context.put("treeCode", genTable.getTreeCode());
            context.put("treeName", genTable.getTreeName());
            context.put("expandColumn", getExpandColumn(genTable));
            context.put("treeParentCode", genTable.getTreeParentCode());
        }
        if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
//            context.put("subTable", genTable.getSubTable());
//            context.put("subTableName", genTable.getSubTableName());
//            context.put("subTableFkName", genTable.getSubTableFkName());
//            context.put("subTableFkClassName", genTable.getSubTableFkName());
            // 设置子表类名
            String subClassName = genTable.getSubTable().getClassName();
            context.put("subClassName", subClassName);
            context.put("subclassName", StringUtils.uncapitalize(subClassName));
//            context.put("subImportList", getImportList(genTable.getSubTable()));
        }
        return context;
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(GenTable table) {
        String useWebType = "templates/vue";
        List<String> templates = new ArrayList<>();
        templates.add("templates/java/domain.java.vm");
        templates.add("templates/java/mapper.java.vm");
        templates.add("templates/java/service.java.vm");
        templates.add("templates/java/serviceImpl.java.vm");
        templates.add("templates/java/controller.java.vm");
        templates.add("templates/xml/mapper.xml.vm");
        templates.add("templates/vue/index.js.vm");
        templates.add("templates/xml/sql.vm");
        if (GenConstants.TPL_CRUD.equals(table.getTplCategory())) {
            templates.add(useWebType + "/index.vue.vm");
        } else if (GenConstants.TPL_TREE.equals(table.getTplCategory())) {
            templates.add(useWebType + "/index-tree.vue.vm");
        } else if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
            templates.add(useWebType + "/index.vue.vm");
        }
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable) {
        String fileName = "";
        String tplCategory = genTable.getTplCategory();
        // 生成包路径
        String packageName = genTable.getPackageName();
        // 生成大写类名
        String className = genTable.getClassName();
        // 生成业务名称
        String BusinessName = genTable.getBusinessName();
        String businessName = StringUtils.uncapitalize(BusinessName);
        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + BusinessName;
        if (template.contains("domain.java.vm")) {
            fileName = StringUtils.format("{}/domain/{}.java", javaPath, className);
        }
        if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, tplCategory)) {
            fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
        } else if (template.contains("mapper.java.vm")) {
            fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
        } else if (template.contains("service.java.vm")) {
            fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
        } else if (template.contains("serviceImpl.java.vm")) {
            fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
        } else if (template.contains("controller.java.vm")) {
            fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
        } else if (template.contains("mapper.xml.vm")) {
            fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
        } else if (template.contains("sql.vm")) {
            fileName = StringUtils.format("{}.sql", businessName);
        } else if (template.contains("index.js.vm")) {
            fileName = StringUtils.format("api/{}/{}.js", businessName, businessName);
        } else if (template.contains("index.vue.vm")) {
            fileName = StringUtils.format("views/{}/{}/{}.vue", genTable.getVueModuleName(), businessName, businessName);
        } else if (template.contains("index-tree.vue.vm")) {
            fileName = StringUtils.format("views/{}/{}/{}.vue", genTable.getVueModuleName(), businessName, businessName);
        }
        return fileName;
    }

    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    private static HashSet<String> getImportList(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        GenTable subGenTable = genTable.getSubTable();
        HashSet<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subGenTable)) {
            importList.add("java.util.List");
        }
        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.util.Date");
                importList.add("com.fasterxml.jackson.annotation.JsonFormat");
                importList.add("org.springframework.format.annotation.DateTimeFormat");
            } else if (!column.isSuperColumn() && GenConstants.TYPE_BIG_DECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 根据列类型获取字典组
     *
     * @param genTable 业务表对象
     * @return 返回字典组
     */
    private static String getDictList(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        Set<String> dictList = new HashSet<>();
        addDictList(dictList, columns);
        if (StringUtils.isNotNull(genTable.getSubTable())) {
            List<GenTableColumn> subColumns = genTable.getSubTable().getColumns();
            addDictList(dictList, subColumns);
        }
        return StringUtils.join(dictList, ", ");
    }

    /**
     * 添加字典列表
     *
     * @param dictList 字典列表
     * @param columns  列集合
     */
    private static void addDictList(Set<String> dictList, List<GenTableColumn> columns) {
        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType())
                    && StringUtils.equalsAny(column.getHtmlType(), new String[]{GenConstants.HTML_SELECT,
                    GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX})) {
                dictList.add("'" + column.getDictType() + "'");
            }
        }
    }

    /**
     * 获取需要在哪一列上面显示展开按钮
     *
     * @param genTable 业务表对象
     * @return 展开按钮列序号
     */
    private static int getExpandColumn(GenTable genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int columnNum = 0;
        for (GenTableColumn column : genTable.getColumns()) {
            if (column.checkList()) {
                columnNum++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName)) {
                    break;
                }
            }
        }
        return columnNum;
    }

}
